package start.spring.basic.util;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;

import start.spring.basic.constant.CacheConstants;
import start.spring.basic.constant.ProConstant;
import start.spring.basic.constant.SysConfigConstant;
import start.spring.basic.dynamic.DsConstant;
import start.spring.basic.dynamic.DynamicJdbc;
import start.spring.basic.dynamic.DynamicRedisDAO;
import start.spring.basic.util.common.StringUtil;

/**
 * 
 * ****************************************************************************
 * 内存缓存的配置信息工具类
 *
 * @author(作者)：xuyongyun	
 * @date(创建日期)：2023年6月14日
 ******************************************************************************
 */
public class MemConfigUtil {
	
	/**
	 * 内存缓存刷新时间，默认1小时
	 */
	private final long cacheTimeOut = 60 * 60 * 1000;
	
	@Autowired
	private DynamicJdbc dao;
	
	@Autowired
    private DynamicRedisDAO redis;

	/**
	 * 获取系统配置参数
	 *	
	 * @param configKey 参数配置key
	 * @return
	 * @since           1.0
	 */
	public String getSysConfig(String configKey) {
		String configValue = null;
		//是否需要刷新缓存
		boolean needRefresh = false;
		JSONObject configValueObj = ProConstant.PRAMS.getJSONObject(configKey);
		if(configValueObj==null||configValueObj.size()==0) {
			//内存中没有缓存需要刷新
			needRefresh = true;
		}else {
			if(!configValueObj.containsKey(SysConfigConstant.KEY_TIMESTAMP)||
					!configValueObj.containsKey(SysConfigConstant.KEY_CONFIGVALUE)) {
				//内存中缓存不符合规范需要刷新
				needRefresh = true;
			}else {
				long oldTimestamp = configValueObj.getLongValue(SysConfigConstant.KEY_TIMESTAMP);
				long newTimestamp = System.currentTimeMillis();
				//内存缓存已超时
				if(cacheTimeOut<(newTimestamp - oldTimestamp)) {
					//缓存已超过规定时间需要刷新
					needRefresh = true;
				}else {
					configValue = configValueObj.getString(SysConfigConstant.KEY_CONFIGVALUE);
				}
			}
		}
		
		//重新刷新缓存
		if(needRefresh) {
			//先从redis获取值
			configValue = redis.get(null, getCacheKey(configKey));
			//未获取到有效值再从数据库查询
			if(StringUtil.isEmpty(configValue)) {
				Map<String,Object> sysConfig = dao.getOne(DsConstant.SYSCONFIG, "SELECT config_key as configKey, config_value as configValue FROM sys_config where config_key = ? ", 
						new String[] {configKey});
				if(sysConfig!=null) {
					configValue = sysConfig.get(SysConfigConstant.KEY_CONFIGVALUE).toString().trim();
				}
			}
			//记录最新的值及刷新时间
			configValueObj.put(SysConfigConstant.KEY_CONFIGVALUE, configValue);
			configValueObj.put(SysConfigConstant.KEY_TIMESTAMP, System.currentTimeMillis());
			
			ProConstant.PRAMS.put(configKey, configValueObj);
		}
		return configValue;
	}
	
	/**
     * 设置cache key
     * 
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return CacheConstants.SYS_CONFIG_KEY + configKey;
    }
}
